const { dialog, app, ipcMain, Menu } = require("electron");
const Store = require("electron-store");
const Types = require("../../const/eventName");

const settingStore = new Store({ name: "settings" });

function openSettingDia(event) {
  dialog
    .showOpenDialog({
      title: "选择保存位置",
      buttonLabel: "确定",
      message: "请选择要文件保存的位置",
      properties: ["openDirectory"],
    })
    .then((paths) => {
      event.sender.send(Types.OPENSETTINGDIAREPLY, paths);
    });
}
function getSettingPath(event) {
  const savaPath = settingStore.get(Types.SETTINGSAVEPATH);
  const defaultPath = app.getPath("documents");
  event.sender.send(Types.GETSETTINGDOCPATHREPLY, savaPath || defaultPath);
}
function setSettingPath(_, path) {
  settingStore.set(Types.SETTINGSAVEPATH, path);
  dialog.showMessageBox({ title: "提示", icon: null, message: "保存成功" });
}

function getOssConfig(event) {
  const ossConfig = settingStore.get(Types.OSSCONFIG) || {};
  const enable =
    ossConfig.region &&
    ossConfig.accessKeyId &&
    ossConfig.accessKeySecret &&
    ossConfig.bucket;
  event.sender.send(Types.GETOSSCONFIGREPLY, {
    ...ossConfig,
    enable,
  });
}
function setOssConfig(_, ossConfig) {
  settingStore.set(Types.OSSCONFIG, ossConfig);
  // 更新是否可用
  const ossEnable =
    ossConfig.region &&
    ossConfig.accessKeyId &&
    ossConfig.accessKeySecret &&
    ossConfig.bucket;
  const menu = Menu.getApplicationMenu();
  const ossSync = menu.getMenuItemById("ossSync");
  const toOss = menu.getMenuItemById("toOss");
  const toLocal = menu.getMenuItemById("toLocal");
  ossSync.checked = ossEnable && !!settingStore.get(Types.OSSSYNCINFO);
  ossSync.enabled = ossEnable;
  toOss.enabled = ossEnable;
  toLocal.enabled = ossEnable;
  dialog.showMessageBox({ title: "提示", icon: null, message: "保存成功" });
  ipcMain.send(Types.OSSSYNCINFOCHANGE, ossSync.checked); //通知是否可以云同步
}

module.exports = {
  openSettingDia,
  getSettingPath,
  setSettingPath,
  getOssConfig,
  setOssConfig,
};
